package com.ruoyi.business.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.ruoyi.business.common.Result;
import com.ruoyi.business.entity.*;
import com.ruoyi.business.entity.dto.HomestayInfoDTO;
import com.ruoyi.business.entity.dto.OrderDetail;
import com.ruoyi.business.entity.dto.SellerFriendsDTO;
import com.ruoyi.business.entity.redis.UserObj;
import com.ruoyi.business.service.*;
import com.ruoyi.business.utils.UserObjHolder;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.ruoyi.business.utils.RedisConstant.LOGIN_USER_KEY;
import static com.ruoyi.business.utils.RedisConstant.LOGIN_USER_TTL;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Ao
 * @since 2024-01-08
 */
@RestController
@RequestMapping("/business/seller")
@Api(value = "商人控制层", tags = "商人相关接口")
public class FrontSellerController {
    @Autowired
    private FrontSellerService sellerService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private FrontFeaturesService featuresService;


    @Autowired
    private FrontHomestayInfoService homestayInfoService;



    @Autowired
    private FrontCommentsService commentsService;


    @Autowired
    private FrontRoomInfoService roomInfoService;


    @Autowired
    private FrontOrdersService ordersService;


    @Autowired
    private FrontComplaintInfoService complaintInfoService;




    @PostMapping("/orderList1")
    @ApiOperation(value = "商家名宿的订单接口")
    public Result<List<Orders>> userOrderList(@RequestBody ReceiveData receiveData) {

//        if (receiveData.getUserId() == null) {
//            return Result.error("需要userId");
//        }
        List<Orders> ordersList = ordersService.list(
                new LambdaQueryWrapper<Orders>()
                        .eq(receiveData.getHomestayid() != null, Orders::getHomestayid, receiveData.getHomestayid())

                        .eq(receiveData.getOrderStatus() != null, Orders::getOrderStatus, receiveData.getOrderStatus())//订单状态(预定订单1，已完成订单2，退款订单3)
        );

        return Result.success(ordersList);

    }

    /**
     * 修改房间信息
     * @param
     * @return
     */
    @PostMapping("/updateRoomInfo")
    public Result<String> updateRoomInfo(@RequestBody RoomInfo roomInfo){

        roomInfoService.updateById(roomInfo);
        return null;
    }

    @Autowired
    private FrontHomestayApplyService homestayApplyService;
    /**
     * 商家资质列表
     * @param status
     * @return
     */
    @GetMapping("/homestayApplyList")
    public Result<List<HomestayApply>> homestayApplyList(Integer status){
        String userid = UserObjHolder.getUserObj().getUserid();
        LambdaQueryWrapper<HomestayApply> l1=new LambdaQueryWrapper<>();
        l1.eq(HomestayApply::getApplicantUserId,userid)
                .eq(status!=null,HomestayApply::getApplyStatus,status);


        List<HomestayApply> list = homestayApplyService.list(l1);

        return Result.success(list);

    }

    /**
     * 新增房间
     * @param roomInfo
     * @return
     */
    @PostMapping("/addRoomInfo")
    public Result<String> addRoomInfo(@RequestBody RoomInfo roomInfo){


        roomInfoService.save(roomInfo);

        return Result.success("新增房间成功");
    }
    @PostMapping("/complaintInfoList")
    @ApiOperation(value = "商家名宿的投诉接口")
    public Result<List<ComplaintInfo>> complaintInfoList(@RequestBody ReceiveData receiveData) {

//        if (receiveData.getUserId() == null) {
//            return Result.error("需要userId");
//        }
        List<ComplaintInfo> complaintInfoList = complaintInfoService.list(
                new LambdaQueryWrapper<ComplaintInfo>()
                        .eq(receiveData.getHomestayid() != null, ComplaintInfo::getHomestayId, receiveData.getHomestayid())

                        .eq(receiveData.getStatus() != null, ComplaintInfo::getStatus, receiveData.getStatus())
        );

        return Result.success(complaintInfoList);

    }


    /**
     * 新增民宿
     * @param homestayInfo
     * @return
     */
    @PostMapping("/addHomestayInfo")
    public Result<String> addHomestayInfo(@RequestBody HomestayInfo homestayInfo){
        homestayInfoService.save(homestayInfo);
        return Result.success("添加民宿成功");
    }


    /**
     * 修改民宿
     */
    @PostMapping("/updateHomestayInfo")
    public Result<String> updateHomestayInfo(@RequestBody HomestayInfo homestayInfo){
        homestayInfoService.updateById(homestayInfo);

        return Result.success("修改民宿信息成功");
    }


    /**
     * 删除民宿
     */
    @GetMapping("/deleteHomestayInfo")
    public Result<String> deleteHomestayInfo(Long id){
        homestayInfoService.removeById(id);

        return Result.success("删除民宿成功");
    }


    /**
     * 新增资质
     */
    @PostMapping("/addHomestayApply")
    public Result<String> addHomestayApply(@RequestBody HomestayApply homestayApply){
        homestayApplyService.save(homestayApply);
        return Result.success("新增资质成功");
    }


    /**
     * 修改资质
     */
    @PostMapping("/updateHomestayApply")
    public Result<String> updateHomestayApply(@RequestBody HomestayApply homestayApply){
        homestayApplyService.updateById(homestayApply);

        return Result.success("修改资质信息成功");
    }


    /**
     * 删除资质
     */
    @GetMapping("/deleteHomestayApply")
    public Result<String> deleteHomestayApply(Long id){
        homestayApplyService.removeById(id);

        return Result.success("删除资质成功");
    }


    /**
     * 查看民宿评论
     */
    @GetMapping("/selectComments")
    public Result<List<Comments>> selectComments(Long id){
        LambdaQueryWrapper<Comments> l1=new LambdaQueryWrapper<>();
        List<Comments> list = commentsService.list(l1);


        return Result.success(list);
    }


    /**
     * 发布（回复）评论
     */
    @PostMapping("/replyComments")
    public Result<String> replyComments(@RequestBody Comments comments){
        comments.setDiscussTime(LocalDateTime.now());
        //拿到父级评论
        Long parentDiscussId = comments.getParentDiscussId();
        LambdaQueryWrapper<Comments> l1=new LambdaQueryWrapper<>();
        l1.eq(Comments::getParentDiscussId,parentDiscussId);
        Comments comments1 = commentsService.getOne(l1);
        comments1.setReplyNum(comments1.getReplyNum()+1);//回复数加一
        commentsService.save(comments);
        commentsService.updateById(comments1);

        return Result.success("回复成功");
    }


    /**
     * 支付接口
     */
    @PostMapping("/payment")
    public Result<String> payment(@RequestBody List<Long> ids){
        for (Long id : ids) {
            LambdaQueryWrapper<Orders> l1=new LambdaQueryWrapper<>();
            Orders orders = ordersService.getById(id);
            orders.setOrderType(11);
            ordersService.updateById(orders);
        }


        return Result.success("支付成功");
    }


    /**
     * 商家个人信息修改
     */
    @PostMapping("updateSellerInfo")
    public Result<String> updateSellerInfo(@RequestBody Seller seller){
        sellerService.updateById(seller);


       return Result.success("修改信息成功");
    }
    /**
     * 商人特色列表
     * @param
     * @return
     */
    @PostMapping("/featuresList")
    public Result<List<Features>> featuresList(@RequestBody ReceiveData receiveData){


        LambdaQueryWrapper<Features> l1=new LambdaQueryWrapper<>();
        l1.eq(Features::getHomestayId,receiveData.getHomestayid())
                .eq(Features::getStatus,receiveData.getStatus());


        List<Features> list = featuresService.list(l1);

        return Result.success(list);
    }

    @PostMapping("/roomList")
    @ApiOperation(value = "商家民宿房间接口")
    public Result<List<RoomInfo>> roomList(@RequestBody ReceiveData receiveData) {


        List<RoomInfo> ordersList = roomInfoService.list(
                new LambdaQueryWrapper<RoomInfo>()
                        .eq(receiveData.getHomestayid() != null, RoomInfo::getHomestayId, receiveData.getHomestayid())

                        .eq(receiveData.getAuditStatus() != null, RoomInfo::getAuditStatus, receiveData.getAuditStatus())
        );

        return Result.success(ordersList);

    }

    //获取订单详情
    @ApiOperation(value = "订单详情", tags = "订单详情")
    @GetMapping("/getdetail")
    public Result<OrderDetail> getDetail(@Param("orderid") Long orderid) {
        if (orderid == null) {
            return Result.error("参数获取失败!");
        }
        //查询订单基本信息
        Orders order = ordersService.getById(orderid);
        if (order == null) {
            return Result.error("订单不存在");

        }
        //将现有的字段赋值
        OrderDetail orderDetail = BeanUtil.copyProperties(order, OrderDetail.class);

        //查询对应订单的民宿地址和商家信息
        HomestayInfo homestay = homestayInfoService.getById(orderDetail.getHomestayid());
        if (homestay == null) {
            return Result.error("商家信息不存在");
        }
        orderDetail.setHomestayaddress(homestay.getHomestayAddress());
        orderDetail.setHomertele(homestay.getHomerTele());

        return Result.success(orderDetail);


    }

    @PostMapping("register")
    public Result<String> register(@RequestBody Seller seller){
        sellerService.save(seller);

        return Result.success("注册成功");
    }


    /**
     * 修改订单接口
     * @param orders
     * @return
     */
    @PostMapping("/updateOrder")
    @ApiOperation(value = "修改订单接口")
    public Result<String> update(@RequestBody Orders orders) {

        ordersService.updateById(orders);

        return Result.success("操作完成");
    }



    /**
     * 这个商人自己的民宿列表
     * @return
     */
    @GetMapping("/homestayInfoList")
    public Result<List<HomestayInfoDTO>> list2(){
        String userid = UserObjHolder.getUserObj().getUserid();
        LambdaQueryWrapper<HomestayInfo> l1=new LambdaQueryWrapper<>();
        l1.eq(HomestayInfo::getSellerId,userid);

        List<HomestayInfo> homestayInfoList = homestayInfoService.list(l1);
        /**
         * 对民宿拿到其对应的评论数
         */
        List<Comments> list = commentsService.list();//所有评论
        List<RoomInfo> list1 = roomInfoService.list();
        List<Features> list2 = featuresService.list();

        List<HomestayInfoDTO> result = new ArrayList<>();

        //遍历民宿
        for (HomestayInfo homestayInfo : homestayInfoList) {
            HomestayInfoDTO homestayInfoDTO = BeanUtil.copyProperties(homestayInfo, HomestayInfoDTO.class);

            Long homestayId = homestayInfo.getHomestayId();

            //获得评论数
            List<Comments> collect = list.stream()
                    .filter(comment -> comment.getHomestayId() == homestayId && comment.getParentDiscussId() == 0)//找到该名宿的父级评论
                    .collect(Collectors.toList());
            int size = collect.size();
            homestayInfoDTO.setNum(size);//获得评论数



            //获得最低价格
            List<RoomInfo> roomInfoList = list1.stream()
                    .filter(item -> item.getHomestayId() == homestayId)
                    .collect(Collectors.toList());

            Float minPrice= Float.valueOf(0);
            if(roomInfoList.size()!=0){
                minPrice = Float.valueOf(roomInfoList.get(0).getRoomPrice());
                for (RoomInfo roomInfo : roomInfoList) {
                    if(roomInfo.getRoomPrice()<minPrice){
                        minPrice= Float.valueOf(roomInfo.getRoomPrice());
                    }
                }
                homestayInfoDTO.setMinPrice(minPrice);
            }




            //获得特色
            List<Features> featuresList = list2.stream()
                    .filter(item -> item.getHomestayId() == homestayId)
                    .collect(Collectors.toList());
            result.add(homestayInfoDTO);

            List<String> list3=new ArrayList<>();
            for (Features features : featuresList) {
                list3.add(features.getFeatureName());
            }
            homestayInfoDTO.setFeaturesList(list3);

        }


        return Result.success(result);
    }

    @GetMapping("/list")
    @ApiOperation(value = "商人列表")
    public List<Seller> list(){
        List<Seller> list = sellerService.list();

        return list;
    }

    //商人注册
    @RequestMapping(value = "/add",method = RequestMethod.POST)
    @ApiOperation(value = "商人注册")
    public Result<String> sign(@RequestBody Seller seller){
        if(seller==null){ return Result.error("数据接收失败");
        }
        LambdaQueryWrapper<Seller> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Seller::getUserid,seller.getUserid());
        Seller one = sellerService.getOne(queryWrapper);
        if(one!=null){
            return Result.error("账号已存在");
        }
        boolean save = sellerService.save(seller);
        if(!save){
            return Result.error("数据保存失败");
        }
        return Result.success("注册成功");


    }

    @GetMapping("/findSeller")
    public Result<Seller> findSeller(){
        String userid = UserObjHolder.getUserObj().getUserid();
        LambdaQueryWrapper<Seller> l1=new LambdaQueryWrapper<>();
        l1.eq(Seller::getUserid,userid);

        Seller seller = sellerService.getOne(l1);
        return Result.success(seller);
    }
    //商人登录
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    @ApiOperation(value = "商人登录")
    public Result<Map<String,Object>> login(@RequestBody Seller seller){
        if(seller==null){
            return Result.error("user为null");
        }

        String userid = seller.getUserid();
        String password = seller.getPassword();

        if(userid==null || password==null){
            return Result.error("账号或者密码不能为空");
        }

        LambdaQueryWrapper<Seller> sellerLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sellerLambdaQueryWrapper.eq(Seller::getUserid,userid);
        Seller dbUser = sellerService.getOne(sellerLambdaQueryWrapper);

        if(dbUser==null){
            return Result.error("账号不存在");
        }

        if(!password.equals(dbUser.getPassword())){

            return Result.error("密码错误");
        }

        //账号密码正确
        //token等于随机字符串加学号，账号用于多次登录删除之前登录的key
        String token = UUID.randomUUID().toString(true).toString()+dbUser.getUserid()+"seller";


        //返回给前端使用的
        HashMap<String, Object> result = new HashMap<>();
        result.put("token", token);
        result.put("userId",dbUser.getUserid());
        result.put("userName",dbUser.getUsername());


        //登录后将信息保存到redis中
        //todo：转json存字符串
        UserObj userObj = BeanUtil.copyProperties(dbUser, UserObj.class);
        userObj.setType("seller");
//
        String userJson = JSONUtil.toJsonStr(userObj);

        /**
         * 加入redis之前，删除这个账号之前登录的key
         */



        String pattern = "*" + dbUser.getUserid()+"seller";
        Set<String> keys = stringRedisTemplate.keys(pattern);
        stringRedisTemplate.delete(keys);

        //存入redis--String类型
        stringRedisTemplate.opsForValue().set(LOGIN_USER_KEY + token, userJson);
        //设置有效期30分钟--String类型
        stringRedisTemplate.expire(LOGIN_USER_KEY + token, LOGIN_USER_TTL, TimeUnit.MINUTES);


        return Result.success(result);





    }

    //获取商人信息
    @ApiOperation(value = "获取商人信息",tags = "获取商人信息")
    @GetMapping("/getinfo")
    public Result<Seller> getinfo(){
        String userid = UserObjHolder.getUserObj().getUserid();
        LambdaQueryWrapper<Seller> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Seller::getUserid,userid);
        Seller seller = sellerService.getOne(queryWrapper);
        return Result.success(seller);
    }

    //商人修改人个人信息
    @ApiOperation(value = "商人修改个人信息" ,tags = "商人修改个人信息")
    @PostMapping("/update")
    public Result<String> update(@RequestBody Seller seller){
        if(seller==null){
            return Result.error("数据获取失败！");
        }
        boolean b = sellerService.updateById(seller);

        if(!b){
            return Result.error("修改失败");
        }
         return Result.success("修改成功!");

    }


    //添加特色信息
    @ApiOperation(value="添加特色信息",tags = "添加特色是信息")
    @PostMapping("/add/feature")
    public Result<String> insert(@RequestBody Features features){
        if(features==null){
            return Result.error("参数获取失败");
        }
        boolean save = featuresService.save(features);
        if(!save){
            return Result.error("数据添加失败！");
        }
        return Result.success("添加成功!");

    }

    //删除特色信息
    @ApiOperation(value = "删除特色",tags = "删除特色")
    @PostMapping("/delete/feature")
    public Result<String> delete(@RequestBody Long featureid){
        if(featureid==null){
            return Result.error("参数获取失败!");

        }
        boolean b = featuresService.removeById(featureid);
        if(!b){
            return Result.error("删除失败！");
        }
        return Result.success("删除成功！");
    }


    /**
     * 修改特色
     */

    @PostMapping("/updateFeatures")
    public Result<String> updateFeatures(@RequestBody Features features){
        featuresService.updateById(features);


        return Result.success("修改特色成功");
    }


}

